//
//  AppDelegate.m
//  LeanCloudChatKit-iOS
//
//  v0.8.5 Created by ElonChan on 16/2/2.
//  Copyright © 2016年 LeanCloud. All rights reserved.
//
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>

#import "AppDelegate.h"
#import "LCCKTabBarControllerConfig.h"
#import "LCCKConstantsDefinition.h"
#import "LCChatKitExample.h"
#import "LCCKUtil.h"
#if __has_include(<ChatKit/LCChatKit.h>)
#import <ChatKit/LCChatKit.h>
#else
#import "LCChatKit.h"
#endif
#import "LCCKLoginViewController.h"

#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
/// Notification become independent from UIKit
@import UserNotifications;
#endif

@interface AppDelegate ()

#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
<UNUserNotificationCenterDelegate>
#endif

@end

@implementation AppDelegate
/*
 兼容使用LaunchImage启动图
 这边去获取启动图
 */
- (void) initAd{
    CGSize viewSize =self.window.bounds.size;
    NSString*viewOrientation =@"Portrait";//横屏请设置成 @"Landscape"
    NSString*launchImage =nil;
    NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    for(NSDictionary* dict in imagesDict) {
        CGSize imageSize =CGSizeFromString(dict[@"UILaunchImageSize"]);
        if(CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]]) {
            launchImage = dict[@"UILaunchImageName"];
        }
    }
    self.oldLaunchView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:launchImage]];
    self.oldLaunchView.frame=self.window.bounds;
    self.oldLaunchView.contentMode=UIViewContentModeScaleAspectFill;
    [self.window addSubview:self.oldLaunchView];
    
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    UIApplication*   app = [UIApplication sharedApplication];
    __block    UIBackgroundTaskIdentifier bgTask;
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    }];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    });
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    
    NSError *setCategoryErr = nil;
    NSError *activationErr  = nil;
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryErr];
    
    [[AVAudioSession sharedInstance] setActive: YES error: &activationErr];
    
    
    [AMapServices sharedServices].apiKey = @"0cd68a9df2d61850e214a962c4ae3a76";
    
    [self registerForRemoteNotification];
    
    [LCChatKitExample invokeThisMethodInDidFinishLaunching];
    
    [self customizeNavigationBar];
    
    
    ////////
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    self.window.backgroundColor = [UIColor whiteColor];
    
    ///////
    
    LCCKLoginViewController *loginViewController = [[LCCKLoginViewController alloc] initWithNibName:NSStringFromClass([LCCKLoginViewController class]) bundle:[NSBundle mainBundle]];
    
    loginViewController.autoLogin = YES;
    
    [loginViewController setClientIDHandler:^(NSString *clientID, NSString *passWord) {
        
        [LCCKUtil showProgressText:@"open client ..." duration:30.0f];
        
        [LCChatKitExample invokeThisMethodAfterLoginSuccessWithClientId:clientID success:^{
            
            if (clientID && passWord) {
                [AVUser logInWithUsernameInBackground:clientID password:passWord block:^(AVUser * _Nullable user, NSError * _Nullable error) {
                    
                    if (error) {
                        [LCCKUtil hideProgress];
                        [LCCKUtil showNotificationWithTitle:@"账号或密码错误"
                                                   subtitle:nil
                                                       type:LCCKMessageNotificationTypeError];
                        
                    } else {
                        
                        
                        
                        [LCCKUtil hideProgress];
                        
                        NSString *subtitle = [NSString stringWithFormat:@"User Id 是 : %@", clientID];
                        [LCCKUtil showNotificationWithTitle:@"登陆成功"
                                                   subtitle:subtitle
                                                       type:LCCKMessageNotificationTypeSuccess];
                        
                        LCCKTabBarControllerConfig *tabBarControllerConfig = [[LCCKTabBarControllerConfig alloc] init];
                        
                        self.window.rootViewController = tabBarControllerConfig.tabBarController;
                    }
                    
                }];
            }
            
        } failed:^(NSError *error) {
            
            [LCCKUtil hideProgress];
            [LCCKUtil showNotificationWithTitle:[error localizedDescription]
                                       subtitle:nil
                                           type:LCCKMessageNotificationTypeError];
        }];
    }];
    
    
    void(^loginWithRootView)() = ^(){
        UINavigationController *nvc = [[UINavigationController alloc]initWithRootViewController:loginViewController];
        
        [self.oldLaunchView removeFromSuperview];
        
        self.window.rootViewController = nvc;
        
        [self.window makeKeyAndVisible];
    };
    
    loginWithRootView();
    
    [self initAd];
    
    AVUser *currentUser = [AVUser currentUser];
    
    if (currentUser != nil) {
        // 用户的 sessionToken 有效
        
        [LCChatKitExample invokeThisMethodAfterLoginSuccessWithClientId:currentUser.username success:^{
            
            [self.oldLaunchView removeFromSuperview];
            
            LCCKTabBarControllerConfig *tabBarControllerConfig = [[LCCKTabBarControllerConfig alloc] init];
            
            self.window.rootViewController = tabBarControllerConfig.tabBarController;
            
            [self.window makeKeyAndVisible];
            
            
        } failed:^(NSError *error) {
            loginWithRootView();
        }];
        
        
    } else {
        
        loginWithRootView();
    }
    
    //通知
    if ([[UIDevice currentDevice].systemVersion floatValue] < 10.0) {
        NSDictionary *notificationPayload;
        @try {
            notificationPayload = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
        } @catch (NSException *exception) {}
        
        // Create a pointer to the Photo object
        [[NSNotificationCenter defaultCenter] postNotificationName:LCCKNotificationContactListDataSourceUpdated object:nil userInfo:notificationPayload];
        
    }
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationWithChild:) name:kmonitoringWithNotification object:nil];
    
    return YES;
}

- (void)notificationWithChild:(NSNotification *)sender {
    
    
    NSString *title = [[sender userInfo] objectForKey:@"title"];
    
    CKAlertViewController *alertVC = [CKAlertViewController alertControllerWithTitle:@"消息" message:title];
    
    CKAlertAction *cancle = [CKAlertAction actionWithTitle:@"确定" handler:^(CKAlertAction *action) {
        [LocalNotification removeLocalNotification];
    }];
    [alertVC addAction:cancle];
    
    UIViewController *currentVC = [self getCurrentVC];
    
    [currentVC presentViewController:alertVC animated:NO completion:nil];
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [LCChatKitExample invokeThisMethodInDidRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
    
//    [LCChatKitExample saveWithInstallationName];
}

- (void)customizeNavigationBar {
    if ([UINavigationBar conformsToProtocol:@protocol(UIAppearanceContainer)]) {
        [UINavigationBar appearance].tintColor = [UIColor whiteColor];
        [[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:18], NSForegroundColorAttributeName : [UIColor whiteColor]}];
        [[UINavigationBar appearance] setBarTintColor:NAVIGATION_COLOR];
        [[UINavigationBar appearance] setTranslucent:NO];
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    [LCChatKitExample invokeThisMethodInApplicationWillResignActive:application];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    [LCChatKitExample invokeThisMethodInApplicationWillTerminate:application];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [LCChatKitExample invokeThisMethodInApplication:application didReceiveRemoteNotification:userInfo];
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
    return YES;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return YES;
}

#pragma -
#pragma mark - Other Method

#pragma mark - 初始化UNUserNotificationCenter
///=============================================================================
/// @name 初始化UNUserNotificationCenter
///=============================================================================

/**
 * 初始化UNUserNotificationCenter
 */
- (void)registerForRemoteNotification {
    // iOS 10 兼容
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
        
#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
        
        // 使用 UNUserNotificationCenter 来管理通知
        UNUserNotificationCenter *uncenter = [UNUserNotificationCenter currentNotificationCenter];
        // 监听回调事件
        [uncenter setDelegate:self];
        //iOS 10 使用以下方法注册，才能得到授权
        [uncenter requestAuthorizationWithOptions:(UNAuthorizationOptionAlert+UNAuthorizationOptionBadge+UNAuthorizationOptionSound)
                                completionHandler:^(BOOL granted, NSError * _Nullable error) {
                                    [[UIApplication sharedApplication] registerForRemoteNotifications];
                                    //TODO:授权状态改变
                                    NSLog(@"%@" , granted ? @"授权成功" : @"授权失败");
                                }];
        // 获取当前的通知授权状态, UNNotificationSettings
        [uncenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            NSLog(@"%s\nline:%@\n-----\n%@\n\n", __func__, @(__LINE__), settings);
            /*
             UNAuthorizationStatusNotDetermined : 没有做出选择
             UNAuthorizationStatusDenied : 用户未授权
             UNAuthorizationStatusAuthorized ：用户已授权
             */
            if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined) {
                NSLog(@"未选择");
            } else if (settings.authorizationStatus == UNAuthorizationStatusDenied) {
                NSLog(@"未授权");
            } else if (settings.authorizationStatus == UNAuthorizationStatusAuthorized) {
                NSLog(@"已授权");
            }
        }];
        
#endif
        
    }
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    else if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
        UIUserNotificationType types = UIUserNotificationTypeAlert |
        UIUserNotificationTypeBadge |
        UIUserNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    } else {
        UIRemoteNotificationType types = UIRemoteNotificationTypeBadge |
        UIRemoteNotificationTypeAlert |
        UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:types];
    }
#pragma clang diagnostic pop
}

#pragma mark UNUserNotificationCenterDelegate

#pragma mark - 添加处理 APNs 通知回调方法
///=============================================================================
/// @name 添加处理APNs通知回调方法
///=============================================================================

#pragma mark -
#pragma mark - UNUserNotificationCenterDelegate Method

#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8

/**
 * Required for iOS 10+
 * 在前台收到推送内容, 执行的方法
 */
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    NSDictionary *userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //TODO:处理远程推送内容
        NSLog(@"%@",userInfo);
        [[NSNotificationCenter defaultCenter] postNotificationName:LCCKNotificationContactListDataSourceUpdated object:nil userInfo:userInfo];
    }
    // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
    completionHandler(UNNotificationPresentationOptionAlert);
}

/**
 * Required for iOS 10+
 * 在后台和启动之前收到推送内容, 点击推送后执行的方法
 */
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)())completionHandler {
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //TODO:处理远程推送内容
        NSLog(@"%@",userInfo);
        [[NSNotificationCenter defaultCenter] postNotificationName:LCCKNotificationContactListDataSourceUpdated object:nil userInfo:userInfo];
    }
    completionHandler();
}

#endif

#pragma mark -
#pragma mark - UIApplicationDelegate Method

/*!
 * Required for iOS 7+
 */
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    //TODO:处理远程推送内容
    NSLog(@"%@", userInfo);
    [[NSNotificationCenter defaultCenter] postNotificationName:LCCKNotificationContactListDataSourceUpdated object:nil userInfo:userInfo];
    // Must be called when finished
    completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark - 实现注册APNs失败接口（可选）
///=============================================================================
/// @name 实现注册APNs失败接口（可选）
///=============================================================================

/**
 * also used in iOS10
 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"%s\n[无法注册远程提醒, 错误信息]\nline:%@\n-----\n%@\n\n", __func__, @(__LINE__), error);
}

- (UIViewController *)getCurrentVC {
    
    UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
    if (!window) {
        return nil;
    }
    UIView *tempView;
    for (UIView *subview in window.subviews) {
        if ([[subview.classForCoder description] isEqualToString:@"UILayoutContainerView"]) {
            tempView = subview;
            break;
        }
    }
    if (!tempView) {
        tempView = [window.subviews lastObject];
    }
    
    id nextResponder = [tempView nextResponder];
    while (![nextResponder isKindOfClass:[UIViewController class]] || [nextResponder isKindOfClass:[UINavigationController class]] || [nextResponder isKindOfClass:[UITabBarController class]]) {
        tempView =  [tempView.subviews firstObject];
        
        if (!tempView) {
            return nil;
        }
        nextResponder = [tempView nextResponder];
    }
    return  (UIViewController *)nextResponder;
}

@end
